package one.bugu.android.demon.ui.activity;

import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;

import com.juefeng.android.framework.LKUtil;
import com.juefeng.android.framework.view.annotation.LKContentView;
import com.juefeng.android.framework.view.annotation.LKInjectView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import one.bugu.android.demon.R;
import one.bugu.android.demon.bean.ExchangeBean;
import one.bugu.android.demon.common.BaseHttpAsycResponceHandler;
import one.bugu.android.demon.common.MyBaseActivity;
import one.bugu.android.demon.constant.Constant;
import one.bugu.android.demon.constant.HttpConstant;
import one.bugu.android.demon.ui.adapter.ExchangeServiceAdapter;
import one.bugu.android.demon.ui.dialog.DialogDelHintBg;
import one.bugu.android.demon.ui.dialog.DialogDelHintV;
import one.bugu.android.demon.ui.widget.BaseTopBarView;
import one.bugu.android.demon.util.PreferencesUtil;
import one.bugu.android.demon.util.StatusBarUtils;

/**
 * 兑换服务
 */
@LKContentView(R.layout.activity_exchange_service)
public class ExchangeServiceActivity extends MyBaseActivity implements View.OnClickListener {
    /**
     * topbar
     */
    @LKInjectView(R.id.btbv_exchange)
    private BaseTopBarView btbvExchange;
    /**
     * 展示列表
     */
    @LKInjectView(R.id.gv_exchange)
    private GridView mGrView;

    private String token;
    /**
     * 列表适配器
     */
    private ExchangeServiceAdapter adapter;
    /**
     * 数据源
     */
    private List<ExchangeBean.DataBean> data;
    /**
     * 底部兑换按钮
     */
    @LKInjectView(R.id.btn_exchange)
    private Button mBtn;

    private String goodsNo;
    /**
     * 弹框
     */
    private DialogDelHintBg dialogHint;
    private DialogDelHintV dialogHintv;
    private String num;
    private String name, name1;

    /**
     * 记录当前兑换的商品的position, 该position是用来将当前的商品进行置灰
     */
    private int curPosition = -1;
    /**
     * 增加的消息语音数量
     */
    private int addMsgNum = 0;
    private int addVoiceNum = 0;
    /**
     * 语音及短信正则
     */
    private String regMsgEx = "[0-9]{1,}条语音";
    private String regVoiceEx = "[0-9]{1,}条短信";


    @Override
    protected void initView() {
        super.initView();
        //设置状态栏
        StatusBarUtils.getInstance().setStatusBar("#FFFFFF", this, btbvExchange, false);

        token = PreferencesUtil.getInstance().getString(ExchangeServiceActivity.this, Constant.TOKEN);
        mBtn.setOnClickListener(this);

        /**
         * 添加弹框文字设置
         */
        dialogHint = new DialogDelHintBg(this, "自选成功！", true);
        dialogHint.setCancleText("取消");
        dialogHint.setOkText("确定兑换");
    }

    @Override
    protected void initData() {
        super.initData();
        getData();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        LKUtil.getHttpManager().postBody(HttpConstant.GETGOODS_URL, map, handler);
    }

    @SuppressLint("HandlerLeak")
    public BaseHttpAsycResponceHandler<ExchangeBean> handler = new BaseHttpAsycResponceHandler<ExchangeBean>(true) {
        @Override
        public void onSuccess(ExchangeBean exchangeBean) {
            super.onSuccess(exchangeBean);
            data = exchangeBean.getData();
            adapter = new ExchangeServiceAdapter(ExchangeServiceActivity.this, data);
            mGrView.setAdapter(adapter);
        }

        @Override
        public void onFailed(int code, String message) {
            super.onFailed(code, message);
        }

        @Override
        public void onError() {
            super.onError();
        }
    };

    @Override
    protected void initEvent() {
        super.initEvent();
        mGrView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //临时保存当前选中的position
                curPosition = position;
                goodsNo = data.get(position).getGoodsNo();
                num = String.valueOf(data.get(position).getUseNum());
                name = data.get(position).getUseCoinName();
                name1 = data.get(position).getGoodsName();
                //切换状态
                mBtn.setEnabled(data.get(position).isLimitGoods());
                mBtn.setSelected(data.get(position).isLimitGoods());

                String convertDesc = data.get(position).getConvertDesc();
                addMsgNum = getNumber(convertDesc, regMsgEx);
                addVoiceNum = getNumber(convertDesc, regVoiceEx);

                //  修改的
                for (int i = 0; i < data.size(); i++) {
                    if (position == i) {//当前选中的Item改变背景颜色
                        data.get(i).setSelect(true);
                    } else {
                        data.get(i).setSelect(false);
                    }
                }
                adapter.notifyDataSetChanged();
            }
        });
        //topBar点击事件处理
        btbvExchange.setEventInterface(new BaseTopBarView.EventInterface() {
            @Override
            public void leftOnClick() {
                finish();
            }

            @Override
            public void leftCloseClick() {

            }

            @Override
            public void rightOnClick() {

            }
        });
    }

    private void getExData(String no) {
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        map.put("goodsNo", no);
        LKUtil.getHttpManager().postBody(HttpConstant.GETGOODS_BGT_URL, map, EXhandler);
    }

    @SuppressLint("HandlerLeak")
    public BaseHttpAsycResponceHandler<String> EXhandler = new BaseHttpAsycResponceHandler<String>(true) {
        @Override
        public void onSuccess(String s) {
            super.onSuccess(s);
            dialogShowfile("兑换成功! ");
            //通知页面刷新数据
            setResult(RESULT_OK);
            String voiceNum = PreferencesUtil.getInstance().getString(ExchangeServiceActivity.this, Constant.VOICENUM, "0");
            String msgNum = PreferencesUtil.getInstance().getString(ExchangeServiceActivity.this, Constant.SHORTMESSAGENUM, "0");
            PreferencesUtil.getInstance().putString(ExchangeServiceActivity.this, Constant.SHORTMESSAGENUM, String.valueOf(Integer.parseInt(msgNum) + addMsgNum));
            PreferencesUtil.getInstance().putString(ExchangeServiceActivity.this, Constant.VOICENUM, String.valueOf(Integer.parseInt(voiceNum) + addVoiceNum));
            //兑换成功后将界面重置, 如果是新人套餐,只能兑换一次,其它不受限制
            mBtn.setEnabled(false);
            mBtn.setSelected(false);
            //更新列表
            List<ExchangeBean.DataBean> data = adapter.getAllData();
            if (null == data) {
                //网络请求刷新数据
                getData();
                return;
            }
            //重置选中状态
            data.get(curPosition).setSelect(false);
            if (curPosition == 0) {  //暂时使用0位置为新人套餐
                //新人套餐,只能兑换一次
                data.get(curPosition).setLimitGoods(false);
            }
            //直接修改数据刷新UI
            adapter.notifyList(data);
        }

        @Override
        public void onFailed(int code, String message) {
            super.onFailed(code, message);
            dialogShowfile(message);
        }

        @Override
        public void onError() {
            super.onError();
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_exchange:
                // 商品兑换
                dialogShow();
                break;
            default:
                break;
        }
    }

    private void dialogShow() {
        dialogHint = new DialogDelHintBg(this, "您将消耗" + num + "个" + name + "兑换" + name1 + "套餐,确认兑换?", true);
        dialogHint.setCancleText("取消");
        dialogHint.setOkText("确定兑换");
        dialogHint.setOnDialogVersionListener(new DialogDelHintBg.OnDialogVersionListener() {
            @Override
            public void onSure() {
                getExData(goodsNo);
                dialogHint.dismiss();
            }

            @Override
            public void onCancel() {
                dialogHint.dismiss();
            }
        });
        dialogHint.show();
    }

    private void dialogShowfile(final String s) {
        dialogHintv = new DialogDelHintV(this, "提示", s, true);
        dialogHintv.setOkText("确定");
        dialogHintv.setOnDialogVersionListener(new DialogDelHintV.OnDialogVersionListener() {
            @Override
            public void onSure() {
                dialogHintv.dismiss();
            }

            @Override
            public void onCancel() {
                // dialogHintv.dismiss();
            }
        });
        dialogHintv.show();
    }

    /**
     * 获取字符串中的数据
     *
     * @return
     */
    private int getNumber(String str, String regEx) {
        try {
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(str);
            String text = m.replaceAll("").trim();
            String regNum = "[^0-9]";
            String number = "0";
            if (!TextUtils.isEmpty(text)) {
                number = Pattern.compile(regNum).matcher(text).replaceAll("").trim();
            }
            return TextUtils.isEmpty(number) ? 0 : Integer.parseInt(number);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
